<template>
  <div class="fuel_station_wraper">
    <!-- <div class="tip_container">
      <div class="tip_container_icon"></div>
      <div class="tip_container_info">
        当前定位附近没有合适的加油站，请确认您所在的油站
      </div>
    </div> -->
    <div class="fuel_title">附近站点</div>
    <div class="other_fuel">
      <div
        class="fuel_container"
        v-for="item in fuelList"
        :key="item.stationId"
      >
        <div class="header_wraper">
          <div class="left">
            <div class="header_avatar">
              <img :src="item.headImg" alt="" v-if="!!item.headImg" />
              <img src="~static/common/header.png" alt="" v-else />
            </div>
            <div class="header_name">
              <div class="title">
                {{ item.stationName }}
              </div>
              <div class="info">
                {{ item.detailRegionData }}
              </div>
            </div>
          </div>
          <!-- <div class="distance">{{getDistances(item.stationLatitude, item.stationLongitude)}}</div> -->
        </div>
        <div class="main_wraper">
          <div
            class="main_card"
            v-for="(val, index) in item.oilList"
            :key="index"
          >
            <div class="name">{{ val.oilName }}</div>
            <div class="price">￥{{ val.oilStationPrice }}</div>
          </div>
        </div>
        <div class="divider_line"></div>
        <footer class="bottom_button">
          <div class="item" @click="gotoAddress(item)">
            <div class="icon nav"></div>
            <div class="text">去这里</div>
          </div>
          <nuxt-link
            class="item"
            :to="
              '/' +
                enterpriseId +
                `/fuel/remit/?stationId=${item.stationId}&stationName=${item.stationName}`
            "
            tag="div"
          >
            <div class="icon remit"></div>
            <div class="text">去付款</div>
          </nuxt-link>
        </footer>
      </div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
import wx from "weixin-js-sdk";
import Qr from "@/components/QrCode";
// import VConsole from "vconsole";
// const vConsole = new VConsole();
// Vue.use(VConsole);
export default {
  head() {
    return {
      title: "选择油站"
    };
  },
  data() {
    return {
      fuelList: [],
      latitude: 0, // 纬度
      longitude: 0 // 经度
    };
  },
  components: {
    Qr: Qr
  },
  mounted() {
    this.init();
  },

  // 组件导航守卫
  beforeRouteEnter(to, from, next) {
    // 修复iOS版微信HTML5 History兼容性问题
    if (to.path !== window.location.pathname) {
      location.assign(to.fullPath);
    }
    next();
  },

  methods: {
    ...mapActions({
      getSdkConfig: "authen/getSdkConfig",
      getSdkConfig2: "authen/getSdkConfig2",
      getSdkConfigNew: "authen/getSdkConfigNew"
    }),
    //  detectDeviceType() {
    //   // 在这里实现设备检测逻辑
    //   // 您可以使用 userAgent 或其他方法来确定设备类型
    //   const userAgent = navigator.userAgent.toLowerCase();
    //   if (/iphone|ipad|ipod/.test(userAgent)) {
    //     return "iOS";
    //   } else if (/android/.test(userAgent)) {
    //     return "Android";
    //   } else {
    //     return "Other";
    //   }
    // },
    init() {
      const that = this;
      this.getSdkConfigNew({
        jsApiList: ["getLocation", "openLocation", "checkJsApi"]
      }).then(res => {
        console.log("res检测sdk结果2222:", res);
        wx.config(res);
        wx.ready(function() {
          wx.checkJsApi({
            jsApiList: ["openLocation"],
            success: res => {
              if (res.errMsg === "checkJsApi:ok") {
                console.log("openLocation检查成功", res);
              } else {
                alert(
                  "你的微信版本太低，不支持微信JS接口,请升级到最新的微信版本！"
                );
              }
            }
          });
        });
        wx.error(function(err) {
          // config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
          console.log("configErr", err);
        });
      });

      // 获取油站信息列表
      this.$axios
        .$get("/appletSelectStationList", {
          params: { enterpriseId: this.enterpriseId }
        })
        .then(res => {
          if (res.retCode != 0) {
            throw new Error("获取油站失败");
          }
          this.fuelList = res.data.stationList || [];
        })
        .catch(err => {
          alert(err);
        });
    },

    // init() {
    //   const that = this;
    //   this.getSdkConfig({
    //     jsApiList: ["getLocation", "openLocation"]
    //   }).then(res => {
    //     console.log(res, "res");
    //     wx.config(res);
    //     if (!sessionStorage.getItem("latitudeValue")) {
    //       setTimeout(() => {
    //         wx.ready(function() {
    //           wx.getLocation({
    //             type: "wgs84",
    //             success: function(res) {
    //               console.log(res, "纬度进度获取成功"); //返回的参数
    //               that.latitude = res.latitude; //纬度，浮点数，范围为90 ~ -90
    //               that.longitude = res.longitude; //经度，浮点数，范围为180 ~ -180。
    //               const data = JSON.stringify({
    //                 latitude: res.latitude,
    //                 longitude: res.longitude
    //               });
    //               sessionStorage.setItem("latitudeValue", data);
    //             },
    //             fail: function(res) {
    //               alert("获取位置失败");
    //             }
    //           });
    //         });
    //       }, 800);
    //     }
    //   });

    //   // 获取油站信息列表
    //   this.$axios
    //     .$get("/appletSelectStationList", {
    //       params: { enterpriseId: this.enterpriseId }
    //     })
    //     .then(res => {
    //       if (res.retCode != 0) {
    //         throw new Error("获取油站失败");
    //       }
    //       this.fuelList = res.data.stationList || [];
    //     })
    //     .catch(err => {
    //       alert(err);
    //     });
    // },

    rad(d) {
      return (d * Math.PI) / 180.0;
    },

    getDistances(lat2, lng2) {
      const { latitude, longitude } =
        JSON.parse(sessionStorage.getItem("latitudeValue")) || {};
      let radLat1 = this.rad(latitude || this.latitude);
      let radLat2 = this.rad(Number(lat2));
      let a = radLat1 - radLat2;
      let b = this.rad(longitude || this.longitude) - this.rad(Number(lng2));
      let s =
        2 *
        Math.asin(
          Math.sqrt(
            Math.pow(Math.sin(a / 2), 2) +
              Math.cos(radLat1) *
                Math.cos(radLat2) *
                Math.pow(Math.sin(b / 2), 2)
          )
        );
      s = s * 6378.137;
      // 输出为公里
      s = Math.round(s * 10000) / 10000;

      let distance = s;
      let distance_str = "";

      if (parseInt(distance) >= 1) {
        // distance_str = distance.toFixed(1) + "km";
        distance_str = distance.toFixed(2) + "km";
      } else {
        // distance_str = distance * 1000 + "m";
        distance_str = (distance * 1000).toFixed(2) + "m";
      }

      return distance_str;
    },

    // 去这里
    gotoAddress(info) {
      // const latitudeInfo = JSON.parse(sessionStorage.getItem("latitudeValue"));
      const latitudeInfo = {};
      latitudeInfo.latitude = parseFloat(info.stationLatitude);
      latitudeInfo.longitude = parseFloat(info.stationLongitude);

      console.log("油站信息：", info);
      console.log("导航信息：", latitudeInfo);

      wx.ready(function() {
        try {
          wx.openLocation({
            latitude: latitudeInfo.latitude,
            longitude: latitudeInfo.longitude,
            name: info.stationName,
            address: info.detailRegionData,
            scale: 18
          });
        } catch (error) {
          console.error("Error in wx.openLocation:", error);
        }
      });

      // wx.openLocation({
      //   latitude: latitudeInfo.latitude, // 纬度，浮点数，范围为90 ~ -90
      //   longitude: latitudeInfo.longitude, // 经度，浮点数，范围为180 ~ -180。
      //   name: info.stationName, // 位置名
      //   address: info.detailRegionData, // 地址详情说明
      //   scale: 18 // 地图缩放级别,整型值,范围从1~28。默认为最大
      // });
    }
  }
};
</script>

<style lang="scss">
.fuel_station_wraper {
  box-sizing: border-box;
  min-height: 100vh;
  background-color: #f5f6f7;
  padding: 0.2rem;
  .tip_container {
    position: absolute;
    top: 0;
    display: flex;
    width: 100%;
    padding: 0.1rem 0.22rem;
    left: 0;
    box-sizing: border-box;
    background-color: #fcb0b6;
    color: #d0312e;
    .tip_container_icon {
      width: 0.3rem;
      height: 0.3rem;
      background: url("../../../static/fuel/tip.png") no-repeat 0 0;
      background-size: 100% 100%;
      margin-right: 0.2rem;
    }
    .tip_container_info {
      font-size: 0.22rem;
    }
  }
  .fuel_title {
    //margin-top: 0.4rem;
    margin-left: 0.16rem;
    line-height: 0.64rem;
    color: #999;
    font-size: 0.28rem;
    font-weight: 500;
  }
  .other_fuel {
    display: flex;
    flex-direction: column;
    width: 100%;
    .fuel_container {
      margin-bottom: 0.2rem;
      padding: 0.3rem 0;
      border-radius: 0.4rem;
      background-color: #fff;
      overflow: hidden;

      .header_wraper {
        display: flex;
        justify-content: space-between;
        padding: 0 0.32rem;
        margin-bottom: 0.32rem;
        .left {
          display: flex;
          .header_avatar {
            width: 0.72rem;
            height: 0.72rem;
            margin-right: 0.2rem;
            img {
              width: 100%;
            }
          }
          .header_name {
            display: flex;
            flex-direction: column;
            .title {
              font-size: 0.32rem;
              max-width: 4rem;
              margin-bottom: 0.12rem;
            }
            .info {
              font-size: 0.24rem;
              color: #999;
            }
          }
        }
        .distance {
          line-height: 0.48rem;
          font-size: 0.24rem;
          color: #999;
        }
      }

      .main_wraper {
        padding: 0 0.32rem;
        display: flex;
        flex-wrap: wrap;
        .main_card {
          width: 1.5rem;
          height: 1.5rem;
          margin: 0 0.08rem 0.08rem 0;
          border-radius: 0.16rem;
          border: 1px solid #f6f6f6;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          &:nth-child(4n) {
            margin: 0 0 0.08rem 0;
          }
          .name {
            font-size: 0.28rem;
            color: #333;
            margin-bottom: 0.1rem;
          }
          .price {
            font-size: 0.32rem;
            color: #32af51;
          }
        }
      }
      .divider_line {
        width: 100%;
        height: 1px;
        margin: 16px 0;
        background-color: #f5f5f5;
      }
      .bottom_button {
        display: flex;
        .item {
          width: 50%;
          display: flex;
          justify-content: center;
          .icon {
            width: 0.4rem;
            height: 0.4rem;
            &.nav {
              background: url("../../../static/fuel/nav.png") no-repeat 0 0;
              background-size: 100% 100%;
            }
            &.remit {
              background: url("../../../static/fuel/remit.png") no-repeat 0 0;
              background-size: 100% 100%;
            }
          }
          .text {
            margin-left: 0.16rem;
            font-size: 0.28rem;
            color: #333;
          }
        }
      }
    }
  }
}
</style>
